package org.ww.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ww.common.to.es.SkuEsModel;
import org.ww.search.config.ElasticSearchConfig;
import org.ww.search.constant.EsConstant;
import org.ww.search.service.MallSearchService;
import org.ww.search.vo.SearchParam;
import org.ww.search.vo.SearchResult;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: gmall
 * @description: MallSearchServiceImpl
 * @author: ww
 * @create: 2024-04-16 14:35
 **/
@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Override
    public SearchResult search(SearchParam searchParam) {
        SearchResult result = null;
        //1、构造查询请求
        SearchRequest searchRequest = buildSearchRequest(searchParam);

        try {
            SearchResponse response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
            //2、构造结果
            result = buildSearchResult(response,searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    //构造检索请求
    private SearchRequest buildSearchRequest(SearchParam param) {
        //构建DSL语句
        SearchSourceBuilder builder = new SearchSourceBuilder();
        /**
         * 查询：，（按照属性，分类，品牌，价格区间，库存）
         */
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //1.1 模糊匹配
        if(StringUtils.isNotBlank(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1.2 filter -- 分类
        if(param.getCatalog3Id() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }

        //1.2 filter -- 品牌
        if(CollectionUtils.isNotEmpty(param.getBrandId())){
            boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId",param.getBrandId()));
        }

        //1.2 filer -- 按照指定的属性进行查询
        /**
         * attrs=1_5寸:8寸&attrs=2_16G:32G
         */
        if(CollectionUtils.isNotEmpty(param.getAttrs())){
            for (String attr : param.getAttrs()) {
                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                String[] attrs = attr.split("_");
                String attrId = attrs[0];
                String[] attrValue = attrs[1].split(":");
                boolQuery.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                boolQuery.must(QueryBuilders.termsQuery("attrs.attrValue",attrValue));
                NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", boolQuery, ScoreMode.None);
                boolQueryBuilder.filter(nestedQueryBuilder);
            }

        }

        //1.2 filer -- 库存
        if(param.getHasStock() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",param.getHasStock().equals(1)));
        }

        //1.2 filer -- 价格区间
        /**
         * 价格 ： 0_500  _500  500_
         */
        if(StringUtils.isNotBlank(param.getSkuPrice())){
            RangeQueryBuilder skuPriceBuilder = QueryBuilders.rangeQuery("skuPrice");
            String[] skuPriceString = param.getSkuPrice().split("_");
            if(skuPriceString.length == 2){
                skuPriceBuilder.gte(skuPriceString[0]);
                skuPriceBuilder.lte(skuPriceString[1]);
            }else{
                if(param.getSkuPrice().startsWith("_")){
                    skuPriceBuilder.lte(skuPriceString[0]);
                }
                if(param.getSkuPrice().endsWith("_")){
                    skuPriceBuilder.gte(skuPriceString[0]);
                }
            }
            boolQueryBuilder.filter(skuPriceBuilder);
        }

        builder.query(boolQueryBuilder);
        /**
         * 排序，分页，高亮
         */

        //2.1 排序:hotScore_asc/desc
        if(StringUtils.isNotBlank(param.getSort())){
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder order = s[0].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            builder.sort(s[0],order);
        }

        //2.2 分页
        builder.from((param.getPageNum() - 1) * EsConstant.SEARCH_PAGESIZE);
        builder.size(EsConstant.SEARCH_PAGESIZE);

        //2.3 高亮
        if(StringUtils.isNotBlank(param.getKeyword())){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            builder.highlighter(highlightBuilder);
        }

        /**
         * 聚合分析
         */
        //1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        //品牌根据名称和图片进行子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        builder.aggregation(brand_agg);

        //2 分类聚合
        TermsAggregationBuilder catelogIdAgg = AggregationBuilders.terms("catelog_id_agg").field("catalogId").size(50);
        //对分类名称进行子聚合
        catelogIdAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        builder.aggregation(catelogIdAgg);

        //3 属性聚合
        //nestes内嵌构建path
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        //根据属性id进行聚合
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id").field("attrs.attrId").size(1);
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value").field("attrs.attrValue").size(1));
        attrAgg.subAggregation(attrIdAgg);
        builder.aggregation(attrAgg);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, builder);

        log.info("构建的DSL:{}",builder.toString());
        return searchRequest;
    }

    private SearchResult buildSearchResult(SearchResponse response,SearchParam param) {
        SearchResult result = new SearchResult();
        //1、返回的所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> skuEsModels = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(Arrays.asList(hits.getHits()))){
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString,SkuEsModel.class);
                if(StringUtils.isNotBlank(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String skuTitleValue = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitleValue);
                }
                skuEsModels.add(skuEsModel);
            }
        }
        result.setProduct(skuEsModels);

        //2、当前所有商品涉及到的所有属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        List<? extends Terms.Bucket> attrIdAggBuckets = attr_id_agg.getBuckets();
        for (Terms.Bucket attrIdAggBucket : attrIdAggBuckets) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //1、获取属性id
            long attrId = Long.parseLong(attrIdAggBucket.getKeyAsString());
            //2、获取名称
            ParsedStringTerms attr_name = attrIdAggBucket.getAggregations().get("attr_name");
            String attrName = attr_name.getBuckets().get(0).getKeyAsString();
            //3、获取属性值
            ParsedStringTerms attr_value = attrIdAggBucket.getAggregations().get("attr_value");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket bucket : attr_value.getBuckets()) {
                String attrValue = bucket.getKeyAsString();
                attrValues.add(attrValue);
            }

            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);
            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
        //3、当前商品涉及到的所有品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        List<? extends Terms.Bucket> brandAggBuckets = brand_agg.getBuckets();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //1、获取品牌id
            long brandId = Long.parseLong(brandAggBucket.getKeyAsString());

            //2、获取品牌名称
            ParsedStringTerms brand_name_agg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();

            //3、获取品牌img
            ParsedStringTerms brand_img_agg = brandAggBucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();

            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);
            brandVos.add(brandVo);
        }

        result.setBrands(brandVos);
        //4、当前商品涉及到的所有分类信息
        ParsedLongTerms catelogIdAgg = response.getAggregations().get("catelog_id_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        List<? extends Terms.Bucket> catelogIdAggBuckets = catelogIdAgg.getBuckets();
        for (Terms.Bucket catelogIdAggBucket : catelogIdAggBuckets) {
            //获取分类id
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            long catalogId = Long.parseLong(catelogIdAggBucket.getKeyAsString());
            //获取分类下的自聚合--分类名称
            ParsedStringTerms catalog_name_agg = catelogIdAggBucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogId(catalogId);
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        //5、分页信息-页码
        result.setPageNum(param.getPageNum());
        //5、分页信息-总记录数
        long total = hits.getTotalHits();
        result.setTotal(total);
        //5、分页信息-总页码计算
        int totalPages = (int)total % EsConstant.SEARCH_PAGESIZE == 0 ? (int)total /EsConstant.SEARCH_PAGESIZE : ((int)total /EsConstant.SEARCH_PAGESIZE + 1);
        result.setTotalPages(totalPages);

        List<Integer> pageNavs = new ArrayList<>();
        for(int i = 1;i<totalPages;i++){
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);
        return result;
    }
}
